import Footer from '@/components/Footer';
import RightContent from '@/components/RightContent';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { PageLoading } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from 'umi';
import { history } from 'umi';
import defaultSettings from '../config/defaultSettings';
import StorageManager from './utils/StorageManager';

import { queryUserInfo } from '@/services/user';

const loginPath = '/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

const getUserInfo = async (id: string) => {
  if (!id) return;
  const { data, code } = await queryUserInfo(id);
  if (!code && data) {
    return data;
  }
  return {} as API.UserInfo;
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings & typeof defaultSettings>;
  currentUser?: API.LoginInfo;
  loading?: boolean;
  authorization?: API.AuthorizationItem[];
  configInfo?: string;
  fetchUserInfo?: (id: string) => Promise<API.UserInfo>;
}> {
  let currentUser: API.LoginInfo | undefined = undefined;
  if (history.location.pathname !== loginPath) {
    currentUser = StorageManager.getLocalStorageSync<API.LoginInfo>('current-user') || currentUser;
  }
  const fetchUserInfo = async (userId = '') => {
    // 没有查询用户详情
    // let _userId = userId;
    // if (!userId) {
    //   currentUser = StorageManager.getLocalStorageSync<API.LoginInfo>('current-user');
    //   _userId = currentUser?.username || '';
    // }
    // if (_userId) {
    //   const res = await queryUserInfo(_userId);
    //   if (!res.code && res.data) {
    //     return res.data;
    //   }
    // }
    return {} as API.UserInfo;
  };
  return {
    currentUser,
    settings: defaultSettings,
    fetchUserInfo,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    // waterMarkProps: {  // 配置水印
    //   content: initialState?.currentUser?.user?.nickname || '',
    // },
    // headerRender: (_, el) => {
    //   return <div style={{ backgroundColor: 'red' }}>{el}</div>;
    // },
    pageTitleRender: false,
    footerRender: () => <Footer />,
    onPageChange: () => {
      // onPageChange--进行页面切换时 登录信息校验等
      return true;
      const { location } = history;
      // crmLogin 页面不处理
      if (location.pathname === '/crmLogin') return;

      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }

      // 如果登录时间过期，重定向到 login
      const currentTime = new Date().getTime();
      const timestamp = initialState?.currentUser?.expire || 0;
      if (currentTime > timestamp) {
        history.push(loginPath);
      }
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children: any) => {
      // if (initialState?.loading) return <PageLoading />;
      return <>{children}</>;
    },
    ...initialState?.settings,
  };
};
